//201902104003邵潇漩
package bysj.service;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;
import bysj.dao.SchoolDao;
import bysj.domain.School;
import bysj.exception.BysjException;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

public final class SchoolService {
	private static SchoolDao schoolDao= SchoolDao.getInstance();
	private static SchoolService schoolService=new SchoolService();
	private SchoolService(){}
	
	public static SchoolService getInstance(){
		return schoolService;
	}

	public Collection<School> findAll(List<Condition> conditionList, Pagination pagination) throws SQLException {
		//获得连接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		Collection<School> schools = schoolDao.findAll(connection,conditionList,pagination);
		JdbcHelper.close(connection);
		return schools;
	}
	
	public School find(Integer id) throws SQLException {
		//获得连接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		School school = schoolDao.find(connection, id);
		JdbcHelper.close(connection);
		return school;
	}

	public boolean update(School school) throws SQLException,BysjException {
		//获得连接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		boolean school_update= false;
		//将自动提交设为false，开始事务
		connection.setAutoCommit(false);
		try{
			school_update=schoolDao.update(connection,school);
			//提交事务
			connection.commit();
		}catch (SQLException e){
			//回滚事务中的所有操作
			connection.rollback();
			if (e.getMessage().equals("Duplicate entry '03' for key 'no'")) {
				throw new BysjException("新添加的学院的编号已经存在");
			}
		}finally {
			//将自动提交设置为false，结束事务
			connection.setAutoCommit(true);
			JdbcHelper.close(connection);
		}
		return school_update;
	}
	
	public boolean add(School school) throws SQLException,BysjException {
		//获得连接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		boolean school_add=false;
		try{
			school_add=schoolDao.add(connection,school);
		}catch(SQLException e){
			if (e.getMessage().equals("Duplicate entry '03' for key 'no'")) {
				throw new BysjException("新添加的学院的编号已经存在");
			}
		}finally {
			JdbcHelper.close(connection);
		}
		return school_add;
	}

	public boolean delete(Integer id) throws SQLException,BysjException {
		School school=this.find(id);
		return this.delete(school);
	}
	
	public boolean delete(School school) throws SQLException,BysjException{
		//获得连接以便完成可能的事务操作
		Connection connection = JdbcHelper.getConn();
		//获得所有下一级单位(Department)的数量
		int countDepartmentsOfSchool = DepartmentService.getInstance().countAll(connection,school);
		//若没有二级单位，则能够删除，否则抛出异常
		if(countDepartmentsOfSchool==0){
			boolean school_del=schoolDao.delete(connection,school);
			JdbcHelper.close(connection);
			return school_del;
		}else{
			JdbcHelper.close(connection);
			throw new BysjException(school.getDescription()+"仍然有下属系，不能删除");
		}
	}
}